<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <link rel="icon" href="/images/favicon.svg" type="image/svg+xml"> -->
    <link rel="alternate icon" href="/images/favicon.ico" type="image/x-icon">
    <title>Yonker system manager</title>

    <style>
        /* 进度条样式 */
        .progress-container {
            height: 20px;
            width: 30%;
            background-color: #f3f3f3;
            border: 1px solid #ccc;
            margin-top: 1px;
            margin-left: 20px;
        }
        .progress-bar {
            height: 99%;
            width: 0%;
            background-color: #4caf50;
        }
    </style>
</head>
<body style="width: 62%; margin: 0 auto;">
    <h1  id="page-title" style="text-align: center;">设备后台管理系统</h1>

    <label style="color: red; ">注意：本页面仅供厂家工程人员使用，错误配置将导致机器无法正常工作。</label>
    <br>
    <label>系统信息：</label><label id="system-info"></label>

    <h3>系统配置:</h3>
    <div id="sys-configs" style="border: 1px solid #4caf50; padding: 10px;">
        <div style="display: flex; width: 100%; background-color: #fafafa;">
            <label style="margin-right: 20px;">主程序</label>
            <form id="main-uploadForm" method="post" enctype="multipart/form-data">
                <input id="main-file" type="file" name="fileUpload"">
                <button type="submit" id="update-mainapp-btn" style="margin-left: 20px;">上传</button>
            </form>

            <!-- 进度条容器 -->
            <div class="progress-container">
                <div class="progress-bar" id="main-upload-progress-bar">
                    <label class="progress-num" id="main-upload-progress-num">0%</label>
                </div>
            </div>
        </div>
        <br>

        <div  style="display: flex; width: 100%; background-color: #fafafa;">
            <label style="margin-right: 32px;">Logo</label>
            <form id="logo-uploadForm" method="post" enctype="multipart/form-data">
                <input id="logo-file" type="file" name="fileUpload"">
                <button type="submit" id="update-logo-btn" style="margin-left: 20px;">上传</button>
            </form>

            <div class="progress-container">
                <div class="progress-bar" id="logo-upload-progress-bar">
                    <label class="progress-num" id="logo-upload-progress-num">0%</label>
                </div>
            </div>
        </div>
        <br>

        <label for="lcd-type">LCD类型:</label>
        <select id="lcd-type" name="lcd-type">
        </select>
    </div>

    <script>
        function updateSysInfo() {
            var cmdToRun = {};
            cmdToRun["cmd"] = "uname -a";

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/cgi-bin/cmd.sh', true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById('system-info').innerText = xhr.responseText;
                } else {
                    alert('命令执行失败');
                }
            }

            xhr.send(JSON.stringify(cmdToRun, null, 4));
        }

        // 监听表单提交
        document.getElementById('main-uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();  // 防止默认表单提交行为
            // 获取文件
            var file = document.getElementById('main-file').files[0];
            if (!file) return;
        
            // 创建 FormData 对象并附加文件
            var formData = new FormData();
            formData.append("file", file);
        
            // 创建 XMLHttpRequest 对象
            var xhr = new XMLHttpRequest();

            // 设置请求方法和URL
            xhr.open("POST", "/cgi-bin/update_app_pack.sh", true);
        
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percent = (e.loaded / e.total) * 100;
                    document.getElementById('main-upload-progress-bar').style.width = percent + '%';
                    document.getElementById('main-upload-progress-bar').style.backgroundColor = '#5facd8';
                    document.getElementById('main-upload-progress-num').innerText = Math.round(percent) + '%';
                    if (percent === 100) {
                        document.getElementById('main-upload-progress-num').innerText = "处理中...";
                    }
                }
            };

            var logoButton = document.getElementById('update-logo-btn');
            logoButton.disabled = true;
        
            // 上传完成后
            xhr.onload = function() {
                logoButton.disabled = false;
                if (xhr.status === 200) {
                    document.getElementById('main-upload-progress-num').innerText = "完成";
                    document.getElementById('main-upload-progress-bar').style.backgroundColor = '#4caf50';
                } else {
                    document.getElementById('main-upload-progress-num').innerText = "错误" + xhr.status;
                    document.getElementById('main-upload-progress-bar').style.backgroundColor = '#af4c4c';
                }
            };
        
            // 上传失败时的处理
            xhr.onerror = function() {
                document.getElementById('main-upload-progress-num').innerText = "错误" + xhr.status;
                document.getElementById('main-upload-progress-bar').style.backgroundColor = '#af4c4c';
            };
        
            // 发送请求
            xhr.send(formData);
        });

        document.getElementById('main-uploadForm').addEventListener('change', function(e) {
            e.preventDefault();
            document.getElementById('main-upload-progress-bar').style.width = '0%';
            document.getElementById('main-upload-progress-num').innerText = '0%';
        });

        // LOGO ============
        document.getElementById('logo-uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();  // 防止默认表单提交行为
            // 获取文件
            var file = document.getElementById('logo-file').files[0];
            if (!file) return;
        
            // 创建 FormData 对象并附加文件
            var formData = new FormData();
            formData.append("file", file);
        
            // 创建 XMLHttpRequest 对象
            var xhr = new XMLHttpRequest();

            // 设置请求方法和URL
            xhr.open("POST", "/cgi-bin/update_logo.sh", true);
        
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percent = (e.loaded / e.total) * 100;
                    document.getElementById('logo-upload-progress-bar').style.width = percent + '%';
                    document.getElementById('logo-upload-progress-bar').style.backgroundColor = '#5facd8';
                    document.getElementById('logo-upload-progress-num').innerText = Math.round(percent) + '%';
                    if (percent === 100) {
                        document.getElementById('logo-upload-progress-num').innerText = "处理中...";
                    }
                }
            };
        
            var mainButton = document.getElementById('update-mainapp-btn');
            mainButton.disabled = true;
        
            // 上传完成后
            xhr.onload = function() {
                mainButton.disabled = false;
                if (xhr.status === 200) {
                    document.getElementById('logo-upload-progress-num').innerText = "完成";
                    document.getElementById('logo-upload-progress-bar').style.backgroundColor = '#4caf50';
                } else {
                    document.getElementById('logo-upload-progress-num').innerText = "错误" + xhr.status;
                    document.getElementById('logo-upload-progress-bar').style.backgroundColor = '#af4c4c';
                }
            };
        
            // 上传失败时的处理
            xhr.onerror = function() {
                document.getElementById('logo-upload-progress-num').innerText = "错误" + xhr.status;
                document.getElementById('logo-upload-progress-bar').style.backgroundColor = '#af4c4c';
            };
        
            // 发送请求
            xhr.send(formData);
        });

        document.getElementById('logo-uploadForm').addEventListener('change', function(e) {
            e.preventDefault();
            document.getElementById('logo-upload-progress-bar').style.width = '0%';
            document.getElementById('logo-upload-progress-num').innerText = '0%';
        });

        // LCD选择
        document.getElementById('lcd-type').addEventListener('change', function() {
            var selectedValue = this.value;
            var selectedText = this.options[this.selectedIndex].text;
            var data = {
                cur_lcd: selectedText, // 提交选中的字符串
                index: selectedValue // 可选：也可以提交值
            };
            
            // 创建XMLHttpRequest对象
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/cgi-bin/update_lcd_type.sh', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            // 监听响应
            xhr.onload = function() {
                if (xhr.status === 200) {
                    // alert('成功');
                } else {
                    alert('修改失败');
                }
            };
            
            // 监听错误
            xhr.onerror = function() {
                alert('网络错误');
            };
            
            // 发送数据
            xhr.send(JSON.stringify(data));
        });
    </script>

    <br>
    <h3>应用配置:</h3>
    <div id="app-configs" style="border: 1px solid #4caf50; padding: 10px;">
    </div>

    <script>
        var args;

        function hasKey(obj, key) {
            return key in obj;
        }

        function postArgs(argsJsonStr) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/cgi-bin/update_args.sh', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    // alert('成功');
                } else {
                    alert('修改失败');
                }
            };
            
            xhr.onerror = function() {
                alert('网络错误');
            };
            
            xhr.send(JSON.stringify(argsJsonStr));
        }

        window.onload = function() {
            updateSysInfo();
            updateLcdType();

            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/cgi-bin/get_args.sh', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }

                    args = JSON.parse(response);
                    var pageTitle = document.getElementById('page-title');
                    if (hasKey(args, 'title')) {
                        pageTitle.innerText = args['title'];
                    }

                    configsArea = document.getElementById('app-configs');
                    for (var key in args) {
                        if (args.hasOwnProperty(key)) {
                            var conf = args[key];
                            if (typeof conf === 'object') {
                                if (hasKey(conf, "options")) {
                                    var label = document.createElement('label');
                                    label.innerText = conf.alias + "： ";
                                    configsArea.appendChild(label);

                                    var select = document.createElement('select');
                                    select.id = key;
                                    for (var i = 0; i < conf.options.length; i++) {
                                        var option = document.createElement('option');
                                        option.value = conf.options[i].name;
                                        option.text = conf.options[i].alias;
                                        if (conf.type === conf.options[i].name) {
                                            option.selected = true;
                                        }
                                        select.add(option);
                                    }
                                    select.addEventListener('change', function() {
                                        args[this.id].type = this.value;
                                        postArgs(args);
                                    });
                                    configsArea.appendChild(select);
                                } else if (hasKey(conf, "list")) {
                                    var label = document.createElement('label');
                                    label.innerText = conf.alias + "： ";
                                    configsArea.appendChild(label);
                                    configsArea.appendChild(document.createElement('br'));

                                    for (var i = 0; i < conf.list.length; i++) {
                                        var itm = conf.list[i];
                                        var checkbox = document.createElement('input');
                                        checkbox.type = "checkbox";
                                        checkbox.name = key;
                                        checkbox.value = i;
                                        checkbox.id = itm.name;
                                        checkbox.checked = itm.selected;
                                        checkbox.addEventListener('change', function() {
                                            args[this.name].list[this.value].selected = this.checked;
                                            postArgs(args);
                                        });
                                        configsArea.appendChild(checkbox);

                                        var label = document.createElement('label');
                                        label.innerText = itm.alias + " ";
                                        label.htmlFor = checkbox.id;
                                        configsArea.appendChild(label);
                                    }
                                } else if (hasKey(conf, "input")) {
                                    var label = document.createElement('label');
                                    label.innerText = conf.alias + "： ";
                                    configsArea.appendChild(label);

                                    var inputGroup = document.createElement('div');
                                    inputGroup.style = "border: 1px solid #29A0CA; padding: 10px; width: 60%;";
                                    configsArea.appendChild(inputGroup);

                                    for (var i = 0; i < conf.input.length; i++) {
                                        var itm = conf.input[i];
                                        var label = document.createElement('label');
                                        label.innerText = itm.alias + "： ";
                                        inputGroup.appendChild(label);

                                        var input = document.createElement('input');
                                        input.style.float = "right";
                                        input.type = "text";
                                        input.class = key;
                                        input.name = itm.name;
                                        input.id = i;
                                        input.value = conf.input[i].text;
                                        input.addEventListener('change', function() {
                                            args[this.class].input[this.id].text = this.value;
                                            postArgs(args);
                                        });
                                        inputGroup.appendChild(input);
                                        inputGroup.appendChild(document.createElement('br'));
                                    }
                                }

                                configsArea.appendChild(document.createElement('br'));
                                configsArea.appendChild(document.createElement('br'));
                            }
                        }
                    }
                }
            };

            xhr.send();
        }

        function updateLcdType() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/cgi-bin/get_lcd_type.sh', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }

                    var args = JSON.parse(response);
                    var lcdTypeSelector = document.getElementById('lcd-type');
                    var curLcdType = args["cur_lcd"];
                    for (var i = 0; i < args["options"].length; i++) {
                        var option = document.createElement('option');
                        option.value = i;
                        option.text = args["options"][i];
                        if (args["options"][i] == curLcdType) {
                            option.selected = true;
                        }
                        lcdTypeSelector.add(option);
                    }
                }
            };

            xhr.send();
        }

        function clearIndicator() {
            document.getElementById('config-args-indicator').innerText = '';
        }
    </script>

    <br>
    <div style="display: flex;">
        <label style="margin-right: 20px;">导入应用配置：</label>
        <form id="appConf-uploadForm" method="post" enctype="multipart/form-data">
            <input id="appConf-file" type="file" name="fileUpload" accept=".json">
            <button type="submit" style="margin-left: 20px;">导入</button>
        </form>
        <button onclick="downloadAppConfigFile()" style="margin-left: 30px;">导出应用配置</button>
    </div>
    <br>

    <script>
        document.getElementById('appConf-uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();  // 防止默认表单提交行为
            // 获取文件
            var file = document.getElementById('appConf-file').files[0];
            if (!file) return;
        
            // 创建 FormData 对象并附加文件
            var reader = new FileReader();
            reader.onload = function(e) {
                var appConf = JSON.parse(e.target.result);
                console.log(appConf);
                postArgs(appConf);
                setTimeout(function(){location.reload();}, 600);
            }
            reader.readAsText(file);
        });
    </script>

    <button onclick="setDateTime()">同步浏览器时间到设备</button>
    <button onclick="runCmd('sync && reboot -f')">重启设备</button>
    <script>
        function downloadAppConfigFile() {
            const jsonStr = JSON.stringify(args, null, 2); // 第二个参数为null，第三个参数为2表示缩进2个空格
            const blob = new Blob([jsonStr], { type: 'application/json' }); // 创建一个Blob对象
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = "app_config.json";
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function runCmd(cmd) {
            var cmdToRun = {};
            cmdToRun["cmd"] = cmd;

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/cgi-bin/cmd.sh', true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            xhr.onload = function() {
                if (xhr.status === 200) {
                    // alert('命令已执行');
                    // document.getElementById('config-args-indicator').innerText = '成功';
                    // document.getElementById('config-args-indicator').style.backgroundColor = '#4caf50';
                    // setTimeout(clearIndicator, 2000);
                } else {
                    alert('命令执行失败');
                    // document.getElementById('config-args-indicator').innerText = '失败';
                    // document.getElementById('config-args-indicator').style.backgroundColor = '#f44336';
                    // setTimeout(clearIndicator, 2000);
                }
            }

            xhr.send(JSON.stringify(cmdToRun, null, 4));
        }

        function setDateTime() {
            var now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 补零使其为两位数
            const date = String(now.getDate()).padStart(2, '0'); // 补零使其为两位数

            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');

            const datetime = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;

            runCmd('date -s \"' + datetime + '\"');
            runCmd('hwclock -wu');
        }
    </script>

    <br><br>

    <div id="terminal-container" style="display: none; margin-top: 20px;">
        <iframe id="shellinabox-terminal" width="100%" height="500px" frameborder="0"></iframe>
    </div>

    <button id="run-cmd-button" onclick="runShellinabox()" style="margin-top: 20px;">Terminal</button>

    <script>
        function runShellinabox() {
            runCmd('killall shellinaboxd');
            setTimeout(function() {
                runCmd('shellinaboxd -b -t');
                document.getElementById('terminal-container').style.display = 'block';
            }, 500);

            var terminal = document.getElementById('shellinabox-terminal');
            terminal.src = 'http://' + window.location.hostname + ':4200';
            terminal.addEventListener('focus', function(event) {
                console.log('Terminal focused');
                event.preventDefault();
            }, true);
            document.getElementById('run-cmd-button').style.display = 'none';
        }
    </script>

    <br><br>
</body>
</html>
